package cn.itcast.realm;


import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SaasRealm extends AuthorizingRealm {


    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;
    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //使用shiro 认证
        //获取页面传递过来的email 和password
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //页面传递过来的email
        String email = token.getUsername();
        char[] password = token.getPassword();
        //页面传递过来的加密后的密码
        String password_page = new String(password);

        //根据email 在数据控中查询到的用户
        User user = userService.findByEmail(email);
        //数据库中的密码
        String password_db = user.getPassword();


        if(user!=null){
            //判断页面传递的密码和数据库中user的密码是否一致
            if(password_page.equals(password_db)){
    //此处需要的三个参数 Object principal, Object credentials 密码, String realmName 当前realm的类名
              return   new SimpleAuthenticationInfo(user,password_db,getName());

            }
        }

        //user 为空 或者密码不相等就会return null;
        return null;
    }
    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        告诉shiro框架 当前登录人有哪些菜单权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();

        System.out.println("-------------------------AuthorizationInfo----------------------------");
        //  根据用户查询所拥有的菜单权限
        List<Module> moduleList = moduleService.findModulesByUser(user);

        for (Module module : moduleList) {
            simpleAuthorizationInfo.addStringPermission(module.getName());
        }

        return simpleAuthorizationInfo;
    }


}
